package com.jbm.onehome.iface;



import com.jbm.core.common.ConnectAgent;
import com.jbm.onehome.common.OHInterface;

import java.io.InputStream;
import java.io.Serializable;

/**
 * Created by root on 16-9-2.
 */
public class PicInputStream extends InputStream  implements Serializable {


	private static final long serialVersionUID = 3593624241865127467L;
	protected IDownloadMedia idm;
	protected IDownloadMedia rtn;
	protected int offset;
 	protected OHInterface iface;
	protected boolean iseof;
	protected ConnectAgent m_ca;

	public PicInputStream ()
	{
		offset = 0;
		iseof = false;
		m_ca = null;
	}

	public PicInputStream ( int folderid, String foldertype, Media media, OHInterface iface, ConnectAgent ca )
	{
		this();

		this.idm = new IDownloadMedia( folderid, foldertype, media );
		this.rtn = new IDownloadMedia( folderid, foldertype, media );
		this.iface = iface;
		m_ca = ca;
	}

	public int read()
	{
		byte b[] = new byte[1];
		int len = read(b);
		if ( len < 0 )
			return len;
		else
			return (b[0] & 0xff);
	}

	public int read(byte b[])
	{
		return read(b,0,b.length);
	}

	public int read(byte b[], int off, int len)
	{
		if (b != null)
		{
			if (off < 0 || len < 0 || len > b.length - off)
			{
				throw new IndexOutOfBoundsException();
			}
		}else if (off < 0 || len < 0)
		{
			throw new IndexOutOfBoundsException();
		}

		if ( this.iseof )
			return -1;

		int rlen = 0;
		do
		{
			if ( offset == rtn.bufferlen )
			{
				offset = 0;
				rtn = iface.GetMediaBlock(idm,m_ca);

				if ( rtn.media.offset == -1 )
				{
					this.iseof = true;
					return rlen;
				}

				idm.media.offset = rtn.media.offset;
				idm.media.mid = rtn.media.mid;
				idm.media.filepath = rtn.media.filepath;
				idm.media.filename = rtn.media.filename;
			}

			if ( rtn.bufferlen > 0 )
			{
				int cplen = ( rtn.bufferlen - offset > len-off-rlen ) ? ( len-off-rlen ):(rtn.bufferlen-offset);
				if ( b != null )
					System.arraycopy(rtn.buffer,offset,b,off+rlen,cplen);
				offset += cplen;
				rlen += cplen;
			}else
				this.iseof = true;
		}while ( rtn.bufferlen > 0 && rlen < len );

		return rlen;
	}

	public long skip(long n)
	{
		return read ( null, 0, (int)n );
	}

	public int available()
	{
		return rtn.bufferlen - offset;
	}

	public void close()
	{
		this.iseof = true;
	}

	public synchronized void mark(int readlimit)
	{

	}

	public synchronized void reset()
	{

	}

	public boolean markSupported()
	{
		return false;
	}
}
